package org.ishequ.miduo;

import java.util.List;
import org.ishequ.miduo.R;
import org.ishequ.miduo.renren.ApiDemoInvoker;
import org.ishequ.renren.api.RenrenApiConfig;
import org.ishequ.weibo.db.UserInfoDBHelper;
import org.ishequ.weibo.domain.UserInfo;
import org.ishequ.weibo.utils.InfoHelper;
import org.ishequ.weibo.utils.http.Download;

import com.renren.api.connect.android.Renren;
import com.renren.api.connect.android.exception.RenrenAuthError;
import com.renren.api.connect.android.view.RenrenAuthListener;

import weibo4android.User;
import weibo4android.Weibo;
import weibo4android.WeiboException;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MiDuoActivity extends Activity {

	/**
	 * weibo's user information database helper
	 */
	private UserInfoDBHelper userInfoDBHelper;
	
	private Weibo weibo;
	private Renren renren;
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
				case InfoHelper.LOADING_INFO_DATA_FAILED:
					Toast.makeText(MiDuoActivity.this, "获取信息失败",
							Toast.LENGTH_LONG).show();
					break;
				case InfoHelper.LOADING_DATA_COMPLETED:
					break;
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		Bundle appState = new Bundle();
		
		System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
		System.setProperty("weibo4j.oauth.consumerSecret",Weibo.CONSUMER_SECRET);

	    LinearLayout layout=(LinearLayout)findViewById(R.id.layout);  
	    //背景自动适应  
//	    autoBackground(this, layout, R.drawable.bg_v, R.drawable.bg_h);  

		// 获取weibo账号列表
		userInfoDBHelper = UserInfoDBHelper.getInstance(this);
		List<UserInfo> userList = userInfoDBHelper.getUserList(true);
		if (userList.isEmpty()) {
			appState.putBoolean(getString(R.string.app_weibo), false);
//			Intent intent = new Intent();
//			intent.setClass(MiDuoActivity.this, AuthorizeActivity.class);
//			startActivity(intent);
		} else {
			/**
			 *  如果不为空读取这些记录的UserID号、Access Token、Access Secret值
			 *  然后根据这3个值调用新浪的api接口获取这些记录对应的用户昵称和用户头像图标等信息。
			 */
			appState.putBoolean(getString(R.string.app_weibo), false);
			updateWeiboUserInfo(this, userList);
		}
		
		//renren
		

	}
	
	//获取Api得到weibo用户信息
	private void updateWeiboUserInfo(Context context, List<UserInfo> userList) {
		//weibo
		for (UserInfo user : userList) {
			if (user != null) {
				weibo = new Weibo();
				weibo.setToken(user.getToken(), user.getTokenSecret());
				User weibo_user = null;
				try {
					weibo_user = weibo.showUser(user.getUserId());
					AppInvoker.initWeibo(weibo);
				} catch (WeiboException e) {
					e.printStackTrace();
				} 
				String imgPath = weibo_user.getProfileImageURL().toString();
				Bitmap userIcon = new Download().downloadImg(imgPath);
				String userName = weibo_user.getScreenName();
				userInfoDBHelper.updateUserInfo(userName, userIcon, user.getUserId());
			}
		}
	}
	
	private void updateRenrenUserInfo() {
		renren = new Renren(RenrenApiConfig.renrenApiKey, RenrenApiConfig.renrenApiSecret, RenrenApiConfig.renrenAppID, MiDuoActivity.this); 
		AppInvoker.initRenren(renren);
		
		//登录的Listener 
		final RenrenAuthListener listener = new RenrenAuthListener() { 
			//登录成功 
			public void onComplete(Bundle values) { 
				handler.post(new Runnable() { 
					@Override 
					public void run() { 
						Toast.makeText(MiDuoActivity.this, MiDuoActivity.this.getString(R.string.auth_success), Toast.LENGTH_SHORT).show(); 
					} 
				}); 
			} 
			//登录失败
			@Override 
			public void onRenrenAuthError(RenrenAuthError renrenAuthError) { 
				handler.post(new Runnable() { 
					@Override 
					public void run() { 
						Toast.makeText(MiDuoActivity.this, MiDuoActivity.this.getString(R.string.auth_failed), Toast.LENGTH_SHORT).show(); 
					} 
				}); 
			} 
			@Override 
			public void onCancelLogin() { 
				
			} 
			@Override 
			public void onCancelAuth(Bundle values) { 
				
			} 
		}; 
		//登录
		renren.authorize(MiDuoActivity.this, new String[]{"read_user_feed"}, listener); 
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		renren.init(this);
	}
	
	

	public static class ConfigHelper {
		public static UserInfo nowUser;
	}

	// 获取屏幕方向
	public static int screenOrient(Activity activity) {
		int orient = activity.getRequestedOrientation();
		if (orient != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
				&& orient != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
			// 宽>高为横屏,反正为竖屏
			WindowManager windowManager = activity.getWindowManager();
			Display display = windowManager.getDefaultDisplay();
			int screenWidth = display.getWidth();
			int screenHeight = display.getHeight();
			orient = screenWidth < screenHeight ? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
					: ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
		}
		return orient;
	}

	public static void autoBackground(Activity activity, View view,
			int Background_v, int Background_h) {
		int orient = screenOrient(activity);
		if (orient == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) { // 纵向
			view.setBackgroundResource(Background_v);
		} else { // 横向
			view.setBackgroundResource(Background_h);
		}
	}

}